package light.mvc.service.workflow.impl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.util.Properties;

import light.mvc.model.sys.Tuser;
import light.mvc.model.workflow.Tform;
import light.mvc.service.ServiceImpl;

import org.jboss.logging.Logger;
import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.task.Assignable;
import org.jbpm.api.task.AssignmentHandler;

public class AssignmentHandlerImpl extends ServiceImpl<Tuser> implements AssignmentHandler {

	private static Logger logger = Logger.getLogger(AssignmentHandlerImpl.class);

	@Override
	public void assign(Assignable assignable, OpenExecution execution) throws Exception {

		Tform form = (Tform) execution.getVariable("form"); // 获取流程变量
		Tuser tuser = form.getApplicant();
		Long userId = tuser.getId();
		String sql1 = "select * from sys_user t where t.id = " + userId;
		Tuser tuser1 = addJdbc(sql1);
//		String sql2 = "select * from sys_user t where t.usertype = 1 and t.organization_id = " + tuser1.getOrganization().getId();
		String sql2 = "select * from sys_user t where t.id = " + tuser1.getSuperior().getId();
		Tuser tuser2 = addJdbc(sql2);

		logger.info("------------AssignmentHandlerImpl.assign to ----------------" + tuser2.getLoginName());
		// 指定当前任务的办理人（分配任务）
		assignable.setAssignee(tuser2.getLoginName());
	}

	private Tuser addJdbc(String sql) {

		ClassLoader loader = this.getClass().getClassLoader();
		InputStream in = loader.getResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String username = p.getProperty("jdbc_username");
		String driverClass = p.getProperty("driverClassName");
		String url = p.getProperty("jdbc_url");
		String password = p.getProperty("jdbc_password");

		Tuser tuser = new Tuser();
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			Class.forName(driverClass);
			conn = DriverManager.getConnection(url, username, password);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				tuser.setLoginName(rs.getString("loginName"));
				tuser.setUsertype(rs.getInt("usertype"));
				Tuser superior = new Tuser();
				superior.setId(Long.valueOf(rs.getInt("superiorId")));
				tuser.setSuperior(superior);
				return tuser;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
